package com.day5;

import com.day4.PacketCodeC;
import com.day4.protocal.command.LoginRequestPacker;
import com.day4.protocal.command.LoginResponsePacket;
import com.day4.protocal.command.MessageResponsePacket;
import com.day4.protocal.command.Packet;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Date;

public class ClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        //创建登录对象
        LoginRequestPacker packer = new LoginRequestPacker();
        packer.setUserId(17);
        packer.setUsername("leonard");
        packer.setPassword("kawhi");

        //编码
        //每次创建客户端连接都要创建这个对象,是不是太浪费空间了
        //功能都是一样的,不妨我们用单例
        //PacketCodeC packetCodec = new PacketCodeC();
        ByteBuf encode = PacketCodeC.INSTANCE.encode(ctx.alloc(),packer);

        //将编码写入到数据中
        ctx.channel().writeAndFlush(encode);
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        Packet packet = PacketCodeC.INSTANCE.decode(byteBuf);
        if (packet instanceof LoginResponsePacket) {
            LoginUtil.markAsLogin(ctx.channel());
            LoginResponsePacket loginResponsePacket = (LoginResponsePacket) packet;

            if (loginResponsePacket.isSuccess()) {
                System.out.println(new Date() + ": 客户端登录成功");
            } else {
                System.out.println(new Date() + ": 客户端登录失败，原因：" + loginResponsePacket.getReason());
            }
        }else if (packet instanceof MessageResponsePacket) {
            MessageResponsePacket messageResponsePacket = (MessageResponsePacket) packet;
            System.out.println(new Date() + ": 收到服务端的消息: " + messageResponsePacket.getMessage());
        }
    }
}
